<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品级联选择框区域 -->
      <el-row class="cate_cascader">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 参数 tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 动态参数 table -->
          <el-table :data="ManyParamsList" border stripe>
            <!-- 表格展开项 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="priamy"
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="attrValClosed(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框或按钮区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 动态参数 table -->
          <el-table :data="OnlyParamsList" border stripe>
            <!-- 展开项 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="priamy"
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="attrValClosed(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框或按钮区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数表单区域 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="paramsFormRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数/属性对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 修改参数/属性表单区域 -->
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="paramsFormRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框选中的值
      selectedKeys: [],
      // 级联选择框的配置
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // tab 标签页数据绑定
      activeName: "many",
      // 动态参数列表
      ManyParamsList: [],
      // 静态属性
      OnlyParamsList: [],
      // 添加参数对话框
      addDialogVisible: false,
      // 添加参数表单数据绑定
      addForm: {
        attr_name: "",
      },
      // 参数表单数据验证规则
      paramsFormRules: {
        attr_name: [
          { required: true, message: "请输入参数内容！", tirgger: "blur" },
        ],
      },
      // 修改参数/属性对话框
      editDialogVisible: false,
      // 修改参数/属性表单数据绑定
      editForm: {},
    };
  },
  created() {
    // 请求商品分类列表
    this.getCateList();
  },
  methods: {
    // 请求商品分类列表
    async getCateList() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("加载商品分类失败！");
      }
      this.cateList = res.data;
    },

    // 监听级联选择框输入发生改变后触发
    handleChange() {
      if(this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.ManyParamsList = []
        this.OnlyParamsList = []
        return 
      }
      // 请求参数列表
      this.getParamsList();
    },

    // 监听 tab 标签栏的切换
    handleTabClick() {
      console.log(this.activeName);
      if (this.selectedKeys.length !== 3) {
        return this.$message.error("请选择商品分类");
      }
      // 请求参数列表
      this.getParamsList();
    },

    // 发送请求获取参数列表
    async getParamsList() {
      let {
        data: res,
      } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes`,
        { params: { sel: this.activeName } }
      );
      // 判断返回的数据状态码
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败！");
      }
      // 对返回的 attr_vals 分割成数组
      res.data.forEach((item) => {
        item.attr_vals = !item.attr_vals ? [] : item.attr_vals.split(" ");
        item.inputVisible = false;
        item.inputValue = "";
      });

      // 根据 tab 标签栏的选项不同给 data 中的数组赋值
      if (this.activeName === "many") {
        this.ManyParamsList = res.data;
      } else {
        this.OnlyParamsList = res.data;
      }
      console.log(res);
    },

    // 关闭添加参数对话框重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 发请求添加参数
    addParams() {
      // 表单预验证
      this.$refs.addFormRef.validate(async (vali) => {
        if (!vali) return;
        let {
          data: res,
        } = await this.$http.post(
          `categories/${this.selectedKeys[2]}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败！");
        }
        this.$message.success("添加成功！");
        this.getParamsList();
        this.addDialogVisible = false;
      });
    },

    // 修改参数/属性对话框的展示
    async showEditDialog(attrId) {
      console.log(attrId);
      // 对话框展示之前根据 attrId 获取数据
      let {
        data: res,
      } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("加载失败！");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },

    // 关闭修改参数/属性对话框重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 发送请求编辑参数/属性
    editParams() {
      this.$refs.editFormRef.validate(async (vali) => {
        if (!vali) return;
        let {
          data: res,
        } = await this.$http.put(
          `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败！");
        }
        this.$message.success("修改成功！");
        this.getParamsList();
        this.editDialogVisible = false;
      });
    },

    // 删除参数/属性
    async removeParams(attrId) {
      let confirm = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirm !== "confirm") {
        return this.$message.info("已取消了删除！");
      }
      let { data: res } = await this.$http.delete(
        `categories/${this.selectedKeys[2]}/attributes/${attrId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败！");
      }
      this.$message.success("删除成功!");
      this.getParamsList();
    },

    // 删除 attr_vals里面的值
    async attrValClosed(index, row) {
      // 根据传来的索引删除数组
      row.attr_vals.splice(index, 1);
      // 发请求修改数据库里的数据
      this.saveAttrVal(row)
    },

    // tag 输入框的内容跟处理
    handleInputConfirm(row) {
      if(row.inputValue.trim().length === 0){
        // 只要焦点或回车提交后就切换回按钮
        row.inputVisible = false;
        row.inputValue = ''
        return
      }

      // 证明此时输入的内容是合法的
      row.attr_vals.push(row.inputValue)
      // 发请求保存到数据库
      this.saveAttrVal(row)
      row.inputValue = ''
      row.inputVisible = false
    },

    // 封装一个方法保存编辑后的参数到数据库
    async saveAttrVal(row) {
      let { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数项失败！");
      }
      this.$message.success('修改参数项成功！')
    },

    // tag 输入框或按钮的显示与隐藏
    showInput(row) {
      row.inputVisible = true;
      // 切换到输入框的时候焦点聚焦在里面
      this.$nextTick((n) => {
        console.log(n);
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  computed: {
    // 动态给 btn 添加 禁用点击
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },

    // 动态添加对话框 title
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态参数";
    },
  },
};
</script>

<style lang="less" scoped>
.cate_cascader {
  margin: 15px 0;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 120px;
}
</style>